<template>
  <a-upload
    :before-upload="beforeUploadDirectory"
    :customRequest="customUploadDirectory"
    :showUploadList="false"
    :max-count="1"
    :accept="imageAccept"
  >
    <a-button :disabled="uploadLoading">
      <UploadOutlined />
      点击上传
    </a-button>
    <div v-if="foldName.length" class="flex items-center">
      <FolderOutlined />
      <div class="ml-1">{{ foldName }}</div>
    </div>
  </a-upload>
  <div v-for="i in imageFileList" :key="i.uid">{{ i.name }}</div>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue'
import type { UploadProps } from 'ant-design-vue'
import { message } from 'ant-design-vue'
import { UploadOutlined, FolderOutlined } from '@ant-design/icons-vue'

let flag = 0
const imageAccept = '.MP4,.mp4,'
const imageFileList = ref<any>([])
const uploadLoading = ref(false)

const foldName = computed(() => {
  const path = imageFileList.value?.[0]?.webkitRelativePath
  return path ? path.substring(0, path.indexOf('/')) : ''
})

const resetDirectoryData = () => {
  flag = 0
  imageFileList.value = []
  uploadLoading.value = false
}

const beforeUploadDirectory: UploadProps['beforeUpload'] = (file) => {
  const fileType = file.name.slice(file.name.lastIndexOf('.') + 1).toLowerCase()

  imageFileList.value = []

  if (imageAccept.includes(fileType)) {
    imageFileList.value.push(file)
    return true
  } else {
    return false
  }
}

const customUploadDirectory = async () => {
  flag++
  if (flag === imageFileList.value?.length) {
    if (imageFileList.value?.length > 1) {
      resetDirectoryData()
      message.error('单次仅支持上传100张图片')
    }
  }
}

defineExpose({ imageFileList })
</script>
